package com.douma.practical_3.external_sort;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;

/**
 * 抖码课堂，专注中国程序员基础内功修炼
 * 官网：douma-tech.com
 * 公众号：资深程序员老汤
 *
 * @作者 : 老汤
 */
public class _1_FileSplit {

    public void splitFile(String bigFileName) throws IOException {
        int fileNum = 0;
        String dir = "data\\sort\\raw_data\\";
        String littleFileName = dir + fileNum;

        // 记录每个小文件包含的整数个数
        long numSize = 0;

        BufferedWriter bw = FileIOUtils.getWriter(littleFileName);

        BufferedReader br = FileIOUtils.getReader(bigFileName);
        String line = null;
        while ((line = br.readLine()) != null) {

            if (numSize > 200000) {
                // 关闭当前小文件的输出流
                FileIOUtils.closeWriter(bw);

                // 拿到下一个小文件的输出流，开始写下一个小文件
                fileNum++;
                littleFileName = dir + fileNum;
                bw = FileIOUtils.getWriter(littleFileName);
                numSize = 0;
            }

            bw.write(line);
            bw.newLine();
            numSize++;
        }

        FileIOUtils.closeReader(br);
    }

    public static void main(String[] args) throws IOException {
        String bigFileName = "data\\sort\\nums.txt";
        new _1_FileSplit().splitFile(bigFileName);
    }
}
